import { login, logout } from '@/api/login';
import { weatherInfoApi } from '@/api/station';
import { getToken, setToken, removeToken,setStorage,getStorage,removeStorage } from '@/utils/auth';

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      userInfo: getStorage('userInfo')||{},
      stationList:getStorage('stationList')||[],
      stationInfo:getStorage('stationInfo')||{},
      weatherInfo:getStorage('weatherInfo')||{},
      messageList:getStorage('messageList')||[],
    }),
    actions: {
      // 登录
      login(userInfo) {
        const loginName = userInfo.loginName.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise(async (resolve, reject) => {
          try {
            let res = await login(loginName, password, code, uuid)
            setToken(res.data.token)
            setStorage('userInfo',res.data)
            this.token = res.data.token
            this.userInfo = res.data
            this.setStationList(res.data.stationList)
            let res1 = await  this.setStationInfo(res.data.stationList[0])
            resolve()
          }catch(err) {}

          // login(loginName, password, code, uuid).then(res => {
          //   setToken(res.data.token)
          //   setStorage('userInfo',res.data)
          //   this.token = res.data.token
          //   this.userInfo = res.data
          //   this.setStationList(res.data.stationList)
          //   this.setStationInfo(res.data.stationList[0])
          //   resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout().then(() => {
            this.token = ''
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 保存用户电站列表
      setStationList(stationList) {
        this.stationList = stationList
        setStorage('stationList',stationList)
      },
      // 保存电站信息
      setStationInfo(stationInfo) {
        this.stationInfo = stationInfo
        setStorage('stationInfo',stationInfo)
        return new Promise((resolve, reject) => {
          weatherInfoApi({id:stationInfo.stationId}).then(res => {
            this.weatherInfo = res.data
            setStorage('weatherInfo',res.data)
            location.reload();
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },

      // 保存消息列表
      setMessageList(data) {
        this.messageList = data
        setStorage('messageList',data)
      },
      
    }
  })

export default useUserStore
